package cn.wyd.shield.support;

import cn.wyd.shield.authentication.exception.AuthenticationException;
import cn.wyd.shield.dto.resp.Message;
import cn.wyd.shield.http.filter.AuthUrlFilter;
import cn.wyd.shield.log.ShieldLog;
import cn.wyd.shield.token.jwt.exception.TokenExpire;
import cn.wyd.shield.token.jwt.exception.TokenIsChange;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@WebFilter("/*")
@Component
public class SupportFilter implements Filter {
    @Autowired
    private ShieldLog shieldLog;
    @Autowired
    private AuthUrlFilter authUrlFilter;
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setCharacterEncoding("utf-8");
        HttpServletResponse httpServletResponse = (HttpServletResponse)servletResponse;

        httpServletResponse.setHeader("Content-Type","application/json");
        HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequest;

        shieldLog.doLog(httpServletRequest);
        try {
            authUrlFilter.doAuth(httpServletRequest);
            filterChain.doFilter(httpServletRequest, httpServletResponse);
        }catch (TokenIsChange e){
            Message message = new Message("ERROR_CERT",e.getMessage());
            httpServletResponse.getWriter().print(JSON.toJSONString(message));
        }catch (TokenExpire e){
            Message message = new Message("ERROR_EXP",e.getMessage());
            httpServletResponse.getWriter().print(JSON.toJSONString(message));
        }catch (AuthenticationException e){
            Message message = new Message("ERROR_FORBIDDEN",e.getMessage());
            httpServletResponse.setStatus(403);
            httpServletResponse.getWriter().print(JSON.toJSONString(message));
        }catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
    }

    public void destroy() {

    }
}
